package com.gyc.game.cchess.model;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class BitPlane implements Cloneable, Serializable {

	public static byte height = 10;

	public static byte width = 9;

	// 不包含的上限
	public static byte MAX = 90;
	// 不包含的下限
	public static byte MIN = -1;

	public static byte getColumn(byte xy) {
		return (byte) (xy % width);
	}

	public static byte getRow(byte xy) {
		return (byte) (xy / width);
	}

	public static byte getX(byte xy) {
		return (byte) (xy % width);
	}

	public static byte getY(byte xy) {
		return (byte) (xy / width);
	}

	byte[] bitArray;

	private byte chessId;

	// private Map<Byte, Byte> occupied = new HashMap<Byte, Byte>();

	public BitPlane() {
		bitArray = new byte[MAX];
	}

	public BitPlane Copy() {
		BitPlane bitPlaneCopy = new BitPlane();
		// FIXME test
		bitPlaneCopy.bitArray = bitArray.clone();

		bitPlaneCopy.setChessId(this.chessId);
		return bitPlaneCopy;
	}

	/**
	 * @return the chessId
	 */
	public byte getChessId() {
		return chessId;
	}

	public byte getXY(final int xy) {
		return bitArray[xy];
	}

	public byte getXY(byte row, byte column) {
		return bitArray[row * width + column];
	}

	public boolean isEmpty() {
		for (byte row = 0; row < height; row++) {
			for (byte column = 0; column < width; column++) {
				if (this.getXY(row, column) != 0) {
					return false;
				}
			}
		}
		return true;
	}

	public void printAsText() {
		for (byte row = 0; row < BitPlane.height; row++) {
			System.out.println();
			for (byte i = 0; i < BitPlane.width; i++) {
				System.out.print(this.getXY(row, i));
				System.out.print("\t");
			}
		}
	}

	public void decode(String array) {
		Arrays.fill(this.bitArray, (byte) 0);

		String[] lines = array.split(" ");

		for (int i = 0; i < lines.length; i++) {
			this.setXY((byte) i, Byte.parseByte(lines[i]));
		}
	}

	public String encode() {
		StringBuilder sb = new StringBuilder();
		for (byte row = 0; row < BitPlane.height; row++) {
			for (byte i = 0; i < BitPlane.width; i++) {
				sb.append("" + (int) this.getXY(row, i));
				sb.append(" ");
			}
		}

		return sb.toString();

	}

	/**
	 * @param chessId
	 *            the chessId to set
	 */
	public void setChessId(byte chessId) {
		this.chessId = chessId;
	}

	public void setXY(byte row, byte column, byte value) {
		// setXY((byte) (row * width + column), value);
		bitArray[row * width + column] = value;
		// this.occupied.put(((byte) (row * width + column)), value);
	}

	public void removeKey(byte xy) {
		// this.occupied.remove(xy);
	}

	public void putKey(byte xy, byte value) {
		// this.occupied.put(xy, value);
	}

	public void setXY(byte xy, byte value) {
		bitArray[xy] = value;
		// this.occupied.put(xy, value);
	}

}
